#include <REGX52.H>
#include "Delay.h"
#include "Key.h"
#include "AT24C02.h"
#include "DS18B20.h"
#include "LCD1602.h"
#include "Timer0.h"
#include "Buzzer.h"
#include "XPT2046.h"

float T,TShow;
char THigh,TLow;
unsigned char KeyNum;
unsigned int Light_Limit;
unsigned int Curr_Light;
void main()
{
	DS18B20_ConvertT();
	Delay(1000);
	THigh = AT24C02_ReadByte(0);
	TLow = AT24C02_ReadByte(1);
	Delay(5);
	if(THigh>125 || TLow<-55 || THigh<TLow)
	{
		THigh = 25;TLow = 20;
	}
	LCD_Init();
	LCD_ShowString(1,1,"T:");
	LCD_ShowString(2,1,"TH:");
	LCD_ShowString(2,10,"TL:");
	Timer0_Init();
	while(1)
	{
		KeyNum = Key();
		DS18B20_ConvertT();
		T = DS18B20_ReadT();
		
		//读取光强限制
		Light_Limit = XPT2046_ReadAD(XPT2046_XP_8); //限制
		//0~255转成0~9
		Light_Limit /= 25;
		Light_Limit -= 1;
		if(Light_Limit < 0)
			Light_Limit = 0;
		//读取光强
		Curr_Light = XPT2046_ReadAD(XPT2046_VBAT_8);//光强
		
		if(T<0)
		{
			TShow = -T;
			LCD_ShowChar(1,3,'-');
		}
		else
		{
			TShow = T;
			LCD_ShowChar(1,3,'+');
		}
		LCD_ShowNum(1,4,TShow,3);
		LCD_ShowChar(1,7,'.');
		LCD_ShowNum(1,8,(unsigned long)(TShow*100)%100,2);
		LCD_ShowSignedNum(2,4,THigh,3);
		LCD_ShowSignedNum(2,13,TLow,3);
		if(KeyNum)
		{
			if(KeyNum==1)
			{
				THigh++;
				if(THigh>=125)
					THigh=125;
			}
			if(KeyNum==2)
			{
				THigh--;
				if(THigh<=TLow)
					THigh++;
			}
			if(KeyNum==3)
			{
				TLow++;
				if(TLow>=THigh)
					TLow--;
			}
			if(KeyNum==4)
			{
				TLow--;
				if(TLow<=-55)
					TLow=-55;
			}
		}
		
		AT24C02_WriteByte(0,THigh);
		Delay(5);
		AT24C02_WriteByte(1,TLow);
		if(T>THigh && Curr_Light <= Light_Limit) 
		{
			LCD_ShowString(1,11,"High!   ");
			Buzzer_Time(100);
		}
		else if(T<TLow)
		{
			LCD_ShowString(1,11,"Low!   ");
			High_Buzzer_Time(100);
		}
		else{
			LCD_ShowString(1,11,"L:");
			LCD_ShowNum(1,13,Curr_Light,2);
			LCD_ShowString(1,15,"|");
			LCD_ShowNum(1,16,Light_Limit,1);
		}
	}
}

unsigned int T0Count;
void Timer0_Routine() interrupt 1
{
	TL0 = 0x66;				//设置定时初始值
	TH0 = 0xFC;				//设置定时初始值
	T0Count++;
	if(T0Count>=20)
	{
		T0Count = 0;
		Key_Loop();
	}
}